package com.ard.camera.demos.service;

import com.ard.camera.demos.DvrHostPingChecker;
import com.ard.camera.demos.config.HostMonitorConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class DvrEmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private HostMonitorConfig config;

    /**
     * 发送硬盘录像机主机监控告警邮件
     */
    public void sendDvrHostAlert(Map<String, List<DvrHostPingChecker.DvrHostCheckResult>> failedDvrHosts) {
        if (failedDvrHosts.isEmpty()) {
            return;
        }

        // 计算总失败主机数
        long totalFailed = failedDvrHosts.values().stream()
                .mapToLong(List::size)
                .sum();

        if (totalFailed == 0) {
            return;
        }

        try {
            String[] toAddresses = config.getEmail().getToAddresses();
            if (toAddresses.length == 0) {
                log.warn("未配置收件人邮箱，跳过发送邮件");
                return;
            }

            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(config.getEmail().getFrom());
            helper.setTo(toAddresses);
            helper.setSubject(config.getEmail().getSubject());

            // 构建HTML邮件内容
            String htmlContent = buildDvrHtmlEmailContent(failedDvrHosts, totalFailed);
            helper.setText(htmlContent, true);

            mailSender.send(message);
            log.info("硬盘录像机告警邮件发送成功，收件人: {}, 涉及硬盘录像机数: {}, 失败主机数: {}",
                    Arrays.toString(toAddresses), failedDvrHosts.size(), totalFailed);

        } catch (Exception e) {
            log.error("发送邮件失败", e);
        }
    }

    /**
     * 构建HTML邮件内容（按硬盘录像机分组）
     */
    private String buildDvrHtmlEmailContent(
            Map<String, List<DvrHostPingChecker.DvrHostCheckResult>> failedDvrHosts,
            long totalFailed) {

        StringBuilder html = new StringBuilder();

        html.append("<!DOCTYPE html>");
        html.append("<html>");
        html.append("<head>");
        html.append("<meta charset=\"UTF-8\">");
        html.append("<style>");
        html.append("body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }");
        html.append(".header { background-color: #f2dede; color: #a94442; padding: 15px; border-radius: 5px; margin-bottom: 20px; }");
        html.append(".info { color: #8a6d3b; background-color: #fcf8e3; padding: 10px; border-radius: 3px; margin-bottom: 15px; }");
        html.append(".dvr-section { margin-bottom: 25px; border: 1px solid #ddd; border-radius: 5px; padding: 15px; }");
        html.append(".dvr-header { background-color: #d9edf7; color: #31708f; padding: 10px; border-radius: 3px; margin-bottom: 10px; }");
        html.append("table { width: 100%; border-collapse: collapse; margin-bottom: 10px; }");
        html.append("th { background-color: #f5f5f5; text-align: left; padding: 8px; border-bottom: 1px solid #ddd; }");
        html.append("td { padding: 8px; border-bottom: 1px solid #ddd; }");
        html.append(".status-failed { color: #d9534f; font-weight: bold; }");
        html.append(".dvr-ip { font-weight: bold; color: #337ab7; }");
        html.append(".footer { margin-top: 20px; color: #777; font-size: 12px; }");
        html.append(".summary { background-color: #f9f9f9; padding: 10px; border-radius: 3px; margin-bottom: 15px; }");
        html.append("</style>");
        html.append("</head>");
        html.append("<body>");

        html.append("<div class=\"header\">");
        html.append("<h2>🚨 硬盘录像机主机监控告警</h2>");
        html.append("</div>");

        html.append("<div class=\"summary\">");
        html.append("<p><strong>检测时间:</strong> ").append(new Date()).append("</p>");
        html.append("<p><strong>涉及硬盘录像机:</strong> ").append(failedDvrHosts.size()).append(" 台</p>");
        html.append("<p><strong>总失败主机数:</strong> ").append(totalFailed).append(" 个</p>");
        html.append("</div>");

        // 按硬盘录像机分组显示
        for (Map.Entry<String, List<DvrHostPingChecker.DvrHostCheckResult>> entry : failedDvrHosts.entrySet()) {
            String dvrIp = entry.getKey();
            List<DvrHostPingChecker.DvrHostCheckResult> failedHosts = entry.getValue();

            if (failedHosts.isEmpty()) {
                continue;
            }

            html.append("<div class=\"dvr-section\">");
            html.append("<div class=\"dvr-header\">");
            html.append("<h3>📹 硬盘录像机: <span class=\"dvr-ip\">").append(dvrIp).append("</span></h3>");
            html.append("<p>失败主机数: ").append(failedHosts.size()).append(" 个</p>");
            html.append("</div>");

            html.append("<table>");
            html.append("<tr>");
            html.append("<th>主机名称</th>");
            html.append("<th>主机IP</th>");
            html.append("<th>尝试次数</th>");
            html.append("<th>状态</th>");
            html.append("</tr>");

            for (DvrHostPingChecker.DvrHostCheckResult result : failedHosts) {
                html.append("<tr>");
                html.append("<td>").append(result.getDvrHostEntry().getHostName()).append("</td>");
                html.append("<td>").append(result.getDvrHostEntry().getHostAddress()).append("</td>");
                html.append("<td>").append(result.getAttempts()).append("</td>");
                html.append("<td class=\"status-failed\">❌ 无法访问</td>");
                html.append("</tr>");
            }

            html.append("</table>");
            html.append("</div>");
        }

        html.append("<div class=\"info\">");
        html.append("<p><strong>说明:</strong> 系统已对以上主机进行多次尝试，但仍无法建立连接。请及时检查相关硬盘录像机网络连接、被监控主机状态以及网络设备配置。</p>");
        html.append("</div>");

        html.append("<div class=\"footer\">");
        html.append("<p>此邮件由硬盘录像机主机监控系统自动发送，请勿直接回复。</p>");
        html.append("<p>如需修改监控配置，请访问系统管理界面。</p>");
        html.append("</div>");

        html.append("</body>");
        html.append("</html>");

        return html.toString();
    }
    /**
     * 发送主机监控告警邮件
     */
    public void sendSMessage(String messageStr) {


        try {
            String[] toAddresses = config.getEmail().getToAddresses();
            if (toAddresses.length == 0) {
                log.warn("未配置收件人邮箱，跳过发送邮件");
                return;
            }

            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(config.getEmail().getFrom());
            message.setTo(toAddresses);
            message.setSubject(config.getEmail().getSubject());
            message.setText(messageStr);

            mailSender.send(message);
            log.info("主机告警邮件发送成功，收件人: {}, 内容: {}",
                    Arrays.toString(toAddresses),  messageStr);

        } catch (Exception e) {
            log.error("发送邮件失败", e);
        }
    }
}